package com.smasher.core.encrypt.oneway;


import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA 工具类
 */
public class SHAUtil {

    public static final String TAG = "SHA";

    /**
     * Sha加密
     *
     * @param string 加密字符串
     * @param type   加密类型 ：{@link SHAType#SHA224}，{@link SHAType#SHA256}，{@link SHAType#SHA384}，{@link SHAType#SHA512}
     * @return SHA加密结果字符串
     */
    public static String sha(String string, @Nullable @SHAType String type) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        if (TextUtils.isEmpty(type)) {
            type = SHAType.SHA256;
        }

        try {
            MessageDigest sha = MessageDigest.getInstance(type);
            byte[] bytes = sha.digest((string).getBytes());

            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "sha: ", e);
        }
        return "";
    }
}
